package http

import (
	"gitee.com/flycash/simple-im/internal/domain"
	"gitee.com/flycash/simple-im/internal/service"
	"github.com/ecodeclub/ginx"
	"github.com/ecodeclub/ginx/session"
	"github.com/gin-gonic/gin"
)

type ChannelHandler struct {
	svc service.ChannelService
}

func NewChannelHandler(svc service.ChannelService) *ChannelHandler {
	return &ChannelHandler{
		svc: svc,
	}
}

func (h *ChannelHandler) PrivateRoutes(server *gin.Engine) {
	message := server.Group("/channel")
	message.POST("/save/lastReadID", ginx.BS[SaveLastReadIDReq](h.SaveLastReadID))
	message.POST("/lastReadID", ginx.BS[GetLastReadIDReq](h.GetLastReadID))
}

func (h *ChannelHandler) SaveLastReadID(ctx *ginx.Context, req SaveLastReadIDReq, sess session.Session) (ginx.Result, error) {
	uid := sess.Claims().Uid
	err := h.svc.UpdateLastMessageID(ctx, uid, domain.ChannelMsgReadRecord{
		ChannelID: req.ChannelID,
		LastMsgID: req.LastMsgID,
	})
	if err != nil {
		return systemErrorResult, err
	}
	return ginx.Result{}, nil
}

func (h *ChannelHandler) GetLastReadID(ctx *ginx.Context, req GetLastReadIDReq, sess session.Session) (ginx.Result, error) {
	uid := sess.Claims().Uid
	lastMsgID, err := h.svc.LastMessageID(ctx, uid, req.ChannelID)
	if err != nil {
		return systemErrorResult, err
	}
	return ginx.Result{Data: lastMsgID}, nil
}
